package com.yingpai.fitness.dvp_2_0.main.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;

import com.bumptech.glide.Glide;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yingpai.fitness.dvp_2_0.common.util.ContextUtil;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

public class WXShareUtil {

    private IWXAPI api;
    private Context context;
    //分享到朋友圈
    public int SHARETOPYQ = 1201;
    //分享给朋友
    public int SHARETOFRIEND = 1202;

    private int THUMB_SIZE = 120;

    public WXShareUtil(Context context) {
        this.context = context;
        api = WXAPIFactory.createWXAPI(context, Contacts.WEIXIN_APP_ID);
    }

    /**
     * 注册到微信
     */
    public void registerWx() {
        if (isWeChatAppInstalled()) {
            api.registerApp(Contacts.WEIXIN_APP_ID);
        } else {
            ToastUtil.showToast("请安装微信客户端");
        }
    }


    public boolean isWeChatAppInstalled() {
        if (api.isWXAppInstalled()) {
            return true;
        } else {
            isAvilible(ContextUtil.getContext(), "com.tencent.mm");
        }
        return false;
    }

    public boolean isAvilible(Context context, String packageName) {
        // 获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        // 用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        // 从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        // 判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

    /**
     * 分享
     *
     * @param url         分享的网址
     * @param title       分享的标题
     * @param description 分享的描述
     * @param flag        分享到朋友圈还是朋友？ 传参SHARETOPYQ/SHARETOFRIEND
     */
    public void share(final String url, final String title, final String description, final String thumb, final int flag) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                WXWebpageObject webpage = new WXWebpageObject();
                webpage.webpageUrl = url;
                final WXMediaMessage msg = new WXMediaMessage(webpage);
                if (flag == SHARETOPYQ) {
                    msg.title = title + "\n" + description;
                } else if (flag == SHARETOFRIEND) {
                    msg.title = title;
                    msg.description = description;
                }
                //Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
                //Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
                //bmp.recycle();
                Bitmap thumbBmp = null;
                try {
                    thumbBmp = Glide.with(context)
                            .load(thumb)
                            .asBitmap() //必须
                            .centerCrop()
                            .into(THUMB_SIZE, THUMB_SIZE)
                            .get();

                    /**
                     * 微信要求缩略图小于64kb
                     * 再次压缩一下
                     * （如果你指定的宽度和高度与当前源位图的宽度和高度相同的话
                     * 就返回源位图，不会创建新位图）
                     */
                    Bitmap bitmap = Bitmap.createScaledBitmap(thumbBmp, THUMB_SIZE, THUMB_SIZE, true);
                    msg.thumbData = Util.bmpToByteArray(bitmap, true);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("webpage");
                req.message = msg;
                if (flag == SHARETOPYQ) {
                    req.scene = SendMessageToWX.Req.WXSceneTimeline;
                } else if (flag == SHARETOFRIEND) {
                    req.scene = SendMessageToWX.Req.WXSceneSession;
                }
                api.sendReq(req);
            }
        }).start();
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

}